package com.example.demo.controller;

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//


import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class HbzzApi {
  private String userId;
  private String apiKey;
  private String apiAddress;
  private static HbzzApi api;

  static {
    if (api == null) {
      api = new HbzzApi();
    }

  }

  private HbzzApi() {
  }

  public static HbzzApi createInstance(String apiAddress, String userId, String apiKey) {
    api.userId = userId;
    api.apiKey = apiKey;
    api.apiAddress = apiAddress;
    return api;
  }

  public byte[] GetApi(String api, HbzzApi.HttpMethod method, Map<String, String> param) throws Exception {
    try {
      Map<String, String> paramToken = new HashMap();
      paramToken.put("userid", this.userId);
      paramToken.put("apikey", this.apiKey);
      String tokenResult = this.request_GetToken(this.apiAddress + "/api/getBtzhDocApi", paramToken);
      JSONObject tokenObj = JSONObject.parseObject(tokenResult);
      boolean success = Boolean.parseBoolean(tokenObj.getString("success"));
      if (success) {
        String token = tokenObj.getJSONObject("data").getString("token");
        String resultGet;
        if (method == HbzzApi.HttpMethod.POST) {
          resultGet = this.request_Post(this.apiAddress + api, token, param, paramToken);
          return resultGet.getBytes("utf-8");
        } else {
          resultGet = this.request_Get(this.apiAddress + api, token, param, paramToken);
          paramToken.remove("x-b3-traceid");
          paramToken.remove("x-b3-spanid");
          paramToken.remove("x-b3-parentspanid");
          return resultGet.getBytes("utf-8");
        }
      } else {
        return tokenResult.getBytes("utf-8");
      }
    } catch (Exception var10) {
      throw var10;
    }
  }

  private String request_GetToken(String url, Map<String, String> param) throws Exception {
    Map<String, String> map = this.sortMap(param);
    String result = "";
    Object in = null;

    try {
      String urlNameString = url + (param.size() > 0 ? "?" + (String)map.get("params") : "");
      URL realUrl = new URL(urlNameString);
      HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
      connection.setConnectTimeout(30000);
      connection.setRequestProperty("userid", this.userId);
      connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
      connection.setRequestProperty("user-agent", "JAVA");
      connection.connect();
      if (connection.getResponseCode() == 200) {
        result = new String(toByteArray(connection.getInputStream()), "UTF-8");
        String traceid = connection.getHeaderField("x-b3-traceid");
        String spanid = connection.getHeaderField("x-b3-spanid");
        String parentspanid = connection.getHeaderField("x-b3-parentspanid");
        System.out.println("traceid：" + traceid + ",spanid:" + spanid + ",parentspanid:" + parentspanid);
        param.put("x-b3-traceid", traceid);
        param.put("x-b3-spanid", spanid);
        param.put("x-b3-parentspanid", parentspanid);
      } else {
        result = new String(toByteArray(connection.getErrorStream()), "UTF-8");
      }
    } catch (Exception var19) {
      throw var19;
    } finally {
      try {
        if (in != null) {
          ((BufferedReader)in).close();
        }
      } catch (Exception var18) {
        var18.printStackTrace();
      }

    }

    return result;
  }

  private String request_Get(String url, String token, Map<String, String> param, Map<String, String> paramToken) throws Exception {
    boolean _flag = false;
    if (param.containsKey("__isuser")) {
      _flag = true;
      param.remove("__isuser");
    }

    Map<String, String> map = this.sortMap(param);
    String result = "";
    Object in = null;

    try {
      String urlNameString = url + (param.size() > 0 ? "?" + (String)map.get("params") : "");
      URL realUrl = new URL(urlNameString);
      HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
      connection.setConnectTimeout(30000);
      connection.setRequestProperty("userid", this.userId);
      if (token != null && !token.equals("")) {
        String sig = this.getMd532((String)map.get("__queryString") + "@" + this.apiKey);
        connection.setRequestProperty("token", token);
        connection.setRequestProperty("sig", sig);
        if (_flag) {
          connection.setRequestProperty("user", "user");
        }
      }

      connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
      connection.setRequestProperty("user-agent", "JAVA");
      if (paramToken.containsKey("x-b3-traceid")) {
        connection.setRequestProperty("x-b3-traceid", (String)paramToken.get("x-b3-traceid"));
      }

      if (paramToken.containsKey("x-b3-spanid")) {
        connection.setRequestProperty("x-b3-spanid", (String)paramToken.get("x-b3-spanid"));
      }

      if (paramToken.containsKey("x-b3-parentspanid")) {
        connection.setRequestProperty("x-b3-parentspanid", (String)paramToken.get("x-b3-parentspanid"));
      }

      connection.connect();
      if (connection.getResponseCode() == 200) {
        result = new String(toByteArray(connection.getInputStream()), "UTF-8");
      } else {
        result = new String(toByteArray(connection.getErrorStream()), "UTF-8");
      }
    } catch (Exception var20) {
      System.out.println("发送GET请求出现异常！" + var20);
      throw var20;
    } finally {
      try {
        if (in != null) {
          ((BufferedReader)in).close();
        }
      } catch (Exception var19) {
        var19.printStackTrace();
      }

    }

    return result;
  }

  private static byte[] toByteArray(InputStream input) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];
    boolean var3 = false;

    int n;
    while(-1 != (n = input.read(buffer))) {
      output.write(buffer, 0, n);
    }

    return output.toByteArray();
  }

  private String request_Post(String url, String token, Map<String, String> param, Map<String, String> paramToken) throws Exception {
    boolean _flag = false;
    if (param.containsKey("__isuser")) {
      _flag = true;
      param.remove("__isuser");
    }

    Map<String, String> map = this.sortMap(param);
    String sig = this.getMd532((String)map.get("__queryString") + "@" + this.apiKey);
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";

    try {
      URL realUrl = new URL(url);
      HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
      conn.setConnectTimeout(30000);
      conn.setRequestProperty("userid", this.userId);
      conn.setRequestProperty("token", token);
      if (_flag) {
        conn.setRequestProperty("user", "user");
      }

      conn.setRequestProperty("sig", sig);
      conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
      conn.setRequestProperty("user-agent", "JAVA");
      if (paramToken.containsKey("x-b3-traceid")) {
        conn.setRequestProperty("x-b3-traceid", (String)paramToken.get("x-b3-traceid"));
      }

      if (paramToken.containsKey("x-b3-spanid")) {
        conn.setRequestProperty("x-b3-spanid", (String)paramToken.get("x-b3-spanid"));
      }

      if (paramToken.containsKey("x-b3-parentspanid")) {
        conn.setRequestProperty("x-b3-parentspanid", (String)paramToken.get("x-b3-parentspanid"));
      }

      conn.setDoOutput(true);
      conn.setDoInput(true);
      out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
      out.print((String)map.get("params"));
      out.flush();
      if (conn.getResponseCode() == 200) {
        result = new String(toByteArray(conn.getInputStream()), "UTF-8");
      } else {
        System.out.println(conn.getResponseCode());
        result = new String(toByteArray(conn.getErrorStream()), "UTF-8");
      }
    } catch (Exception var20) {
      System.out.println("发送 POST 请求出现异常！" + var20);
      throw var20;
    } finally {
      try {
        if (out != null) {
          out.close();
        }

        if (in != null) {
          ((BufferedReader)in).close();
        }
      } catch (IOException var19) {
        var19.printStackTrace();
      }

    }

    return result;
  }

  private String getMd532(String inStr) {
    try {
      MessageDigest alg = MessageDigest.getInstance("MD5");
      alg.update(inStr.getBytes("UTF-8"));
      return this.byteArrayToHex(alg.digest());
    } catch (Exception var3) {
      var3.printStackTrace();
      return "";
    }
  }

  private String byteArrayToHex(byte[] byteArray) {
    char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    char[] resultCharArray = new char[byteArray.length * 2];
    int index = 0;
    byte[] var8 = byteArray;
    int var7 = byteArray.length;

    for(int var6 = 0; var6 < var7; ++var6) {
      byte b = var8[var6];
      resultCharArray[index++] = hexDigits[b >>> 4 & 15];
      resultCharArray[index++] = hexDigits[b & 15];
    }

    return new String(resultCharArray);
  }

  private Map<String, String> sortMap(Map<String, String> map) {
    if (map.isEmpty()) {
      map.put("__queryString", "{}");
      map.put("params", "");
      return map;
    } else {
      Map<String, String> sortMap = new TreeMap(new Comparator<String>() {
        public int compare(String str1, String str2) {
          return str1.compareTo(str2);
        }
      });
      sortMap.putAll(map);
      String queryString = "";

      String key;
      String value;
      for(Iterator var5 = sortMap.keySet().iterator(); var5.hasNext(); queryString = queryString + key + "=" + value + "&") {
        key = (String)var5.next();
        value = (String)sortMap.get(key);
      }

      queryString = queryString.substring(0, queryString.length() - 1);
      sortMap.put("__queryString", "{" + queryString + "}");
      sortMap.put("params", queryString);
      return sortMap;
    }
  }

  public static enum HttpMethod {
    GET,
    POST;

    private HttpMethod() {
    }
  }
}
